package com.example.no1admin.service.impl;

import com.example.no1admin.ex.ServiceException;
import com.example.no1admin.mapper.PackagesMapper;
import com.example.no1admin.mapper.PictureMapper;
import com.example.no1admin.mapper.RouteMapper;
import com.example.no1admin.pojo.dto.route.RouteAddNewDTO;
import com.example.no1admin.pojo.dto.route.RouteUpdateDTO;
import com.example.no1admin.pojo.entity.Picture;
import com.example.no1admin.pojo.entity.Route;
import com.example.no1admin.pojo.vo.packages.PackagesListItemVO;
import com.example.no1admin.pojo.vo.route.RouteDetailVO;
import com.example.no1admin.pojo.vo.route.RouteListItemVO;
import com.example.no1admin.restful.JsonPage;
import com.example.no1admin.service.IRouteService;
import com.example.no1admin.web.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class RouteServiceImpl implements IRouteService {

    @Autowired
    private RouteMapper routeMapper;
    @Autowired
    private PackagesMapper packagesMapper;
    @Autowired
    private PictureMapper pictureMapper;


    public RouteServiceImpl() {
        log.debug("创建业务逻辑对象：RouteServiceImpl");
    }


    @Override
    public void addNew(RouteAddNewDTO routeAddNewDTO) {
        log.debug("开始处理创建拍摄路线的业务，参数：{}", routeAddNewDTO);
        if (routeAddNewDTO.getUrl()!=null){
            int count = pictureMapper.countByUrl(routeAddNewDTO.getUrl());
            if(count!=1){
                String message = "路线图片不存在！";
                log.error(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
            Picture picture = new Picture();
            picture.setAlbumId(routeAddNewDTO.getAlbumId());
            picture.setUrl(routeAddNewDTO.getUrl());
            picture.setIsCover(1);
            int rows = pictureMapper.updateByUrl(picture);
            if(rows!=1){
                String message = "图片上传失败，服务器忙，请稍后再次尝试！";
                log.error(message);
                throw new ServiceException(ServiceCode.ERR_INSERT, message);
            }
        }
        // 检查此拍摄路线（尝试创建的拍摄路线）的名称有没有被使用
        // 如果已经被使用，则不允许创建
        String name = routeAddNewDTO.getName();
        int count = routeMapper.countByName(name);
        if (count > 0) {
            String message = "创建拍摄路线失败，拍摄路线名称【" + name + "】已经被占用！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 创建实体对象（Mapper的方法的参数是实体类型）
        Route route = new Route();

        // 将当前方法参数的值复制到Brand实体类型的对象中
        BeanUtils.copyProperties(routeAddNewDTO, route);
        // 补全属性值（不由客户端提交的属性的值，应该在插入之前补全）

        // 将拍摄风格数据写入到数据库中
        log.debug("即将向表中写入数据：{}", route);
        int rows = routeMapper.insert(route);
        if (rows != 1) {
            String message = "创建拍摄路线失败，服务器忙，请稍后再次尝试！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

    }

    @Override
    public List<RouteListItemVO> list() {
        List<RouteListItemVO> lists = routeMapper.list();
        for (RouteListItemVO list : lists) {
            String url =  pictureMapper.getUrlByAlbumIdAndIsCover(list.getAlbumId());
            log.debug("查询到url{}",url);
            list.setUrl(url);
        }
        return lists;
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理删除拍摄路线的业务，id参数：{}", id);

        //检查拍摄线路是否存在
        RouteDetailVO routeDetailVO = routeMapper.getById(id);
        if (routeDetailVO==null){
            String message = "删除拍摄路线失败，拍摄路线不存在，请刷新！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        List<PackagesListItemVO> packagesList = packagesMapper.list();
        for(PackagesListItemVO packages :packagesList){
            if(packages.getRouteId().equals(id)){
                String message = "删除拍摄路线失败，"+packages.getName()+"套餐内包含该路线,请核验！";
                throw new ServiceException(ServiceCode.ERR_DELETE,message);
            }
        }
        int rows = routeMapper.deleteById(id);
        if (rows!=1){
            String message = "删除拍摄路线失败，服务器忙，请稍后再次尝试！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void updateById(RouteUpdateDTO routeUpdateDTO) {

        log.debug("id:{}enable:{}",routeUpdateDTO.getId(),routeUpdateDTO.getEnable());
        RouteDetailVO routeDetail = routeMapper.getById(routeUpdateDTO.getId());
        if (routeDetail==null){
            String message = "修改拍摄路线失败，拍摄路线不存在，请刷新！";
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
        List<PackagesListItemVO> packagesList = packagesMapper.list();
        for(PackagesListItemVO packages :packagesList){
            if(packages.getRouteId().equals(routeUpdateDTO.getId())){
                String message = "删除拍摄路线失败，"+packages.getName()+"套餐内包含该路线,请核验！";
                throw new ServiceException(ServiceCode.ERR_DELETE,message);
            }
        }
        Route route = new Route();
        BeanUtils.copyProperties(routeUpdateDTO,route);

        int rows = routeMapper.updateById(route);
        if (rows!=1){
            String message = "修改拍摄路线失败，服务器忙，请稍后再次尝试！";
            throw new ServiceException(ServiceCode.ERR_UNKNOWN,message);
        }
    }

    @Override
    public JsonPage<RouteListItemVO> getRouteByPage(Integer pageNum, Integer pageSize) {

            PageHelper.startPage(pageNum,pageSize);
            List<RouteListItemVO> list=routeMapper.list();
            return JsonPage.restPage(new PageInfo<>(list));

    }


}
